//
//  WrapNavigationController.swift
//  Test
//
//  Created by rui on 2018/5/29.
//  Copyright © 2018年 qewqw. All rights reserved.
//

import UIKit

class WrapNavigationController: UINavigationController {

    weak var wrapViewController: WrapViewController?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.interactivePopGestureRecognizer?.isEnabled = false
    }
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        let nav = self.navigationController
        let wrapVc = WrapViewController()
        wrapVc.contentViewController = viewController
        if let item = viewController.customBackItem() {
           viewController.navigationItem.leftBarButtonItem = item
        }else {
           viewController.navigationItem.leftBarButtonItem = configBackItem()
        }
        let count = nav?.viewControllers.count ?? 0
        if count > 0 {
            wrapVc.hidesBottomBarWhenPushed = true
        }
        nav?.pushViewController(wrapVc, animated: animated)
    }
    
    func configBackItem() -> UIBarButtonItem {
        let barItem = UIBarButtonItem(image: #imageLiteral(resourceName: "nav_icon_back"), style: .plain, target: self, action: #selector(back))
        return barItem
    }
    
    @objc func back() {
        let _ = popViewController(animated: true)
    }
    
    override func popViewController(animated: Bool) -> UIViewController? {
        let count = self.navigationController?.viewControllers.count ?? 0
        if count > 1 {
            return self.navigationController?.popViewController(animated:animated)
        }
        return super.popViewController(animated: animated)
    }
    
    override func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
        guard let wrapNavi = viewController.navigationController as? WrapNavigationController else {
            return nil
        }
        guard let wrapVc = wrapNavi.wrapViewController else {
            return nil
        }
        return self.navigationController?.popToViewController(wrapVc, animated: animated)
    }
    
    override func popToRootViewController(animated: Bool) -> [UIViewController]? {
        return self.navigationController?.popToRootViewController(animated: animated)
    }
    
}
